package com.netease.web.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.netease.web.pojo.Content;
import com.netease.web.pojo.Person;
import com.netease.web.pojo.model.User;
import com.netease.web.pojo.model.Returning;
import com.netease.web.service.impl.contServiceImpl;
import com.netease.web.service.impl.personServiceImpl;
import com.netease.web.service.impl.trxServiceImpl;

@RequestMapping(value = "/api")
public class apiController {
	personServiceImpl personService = new personServiceImpl();
	trxServiceImpl trxService = new trxServiceImpl();
	contServiceImpl contentService = new contServiceImpl();
	
	@RequestMapping(value = "/login")
	public @ResponseBody Returning Login(@RequestParam(value = "userName") String userName, 
			@RequestParam(value = "password") String password, HttpServletRequest request){
		Person person = personService.getPersonByUserName(userName);
		Returning body;
		if(!person.getUserName().equals(userName)){
			body = new Returning(203,"worry username", false);
		}
			else if (!person.getPassword().equals(password)) {
				body = new Returning(204, "worry password", false);
			}
				else {
					HttpSession session = request.getSession();
					User user = new User();
					user.setId(person.getId());
					user.setUsername(person.getNickName());
					user.setUsertype(person.getUserType());
					session.setAttribute("user", user);
					
					body = new Returning(200, "seccess", true);
				}
		return body;
	}
	
	@RequestMapping(value="/delete")
	public @ResponseBody Returning deleteContent(@RequestParam(value = "id") int contentId){
		int count = 0;
		Returning body;
		count = contentService.deleteContentById(contentId);
		if(count > 0){
			body = new Returning(200, "success", true);
		}
		else {
			body = new Returning(201, "worry", false);
		}
		return body;
	}
	
	@RequestMapping(value = "/buy")
	public @ResponseBody Returning buyAction(@RequestParam(value = "id") int contentId, HttpServletRequest request){
		int count = 0;
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		Content content = contentService.getContentById(contentId);
		Returning body;
		count = trxService.insertTrx(contentId, user.getId(), content.getPrice(), new Date().getTime());
		if(count > 0){
			body = new Returning(200, "success", true);
		}
		else {
			body = new Returning(201, "worry", false);
		}
		return body;
	}
}
